<template>
  <div class="add_good">
          <!-- 导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 视图 -->
    <el-card >
      <!-- 提示 -->
       <el-alert title="添加商品信息" type="info" center show-icon :closable='false'>
       </el-alert>
       <!-- 步骤条 -->
       <el-steps :space="200" :active="actives-0" finish-status="success" align-center>
          <el-step title="基本信息"></el-step>
          <el-step title="商品参数"></el-step>
          <el-step title="商品属性"></el-step>
          <el-step title="商品图片"></el-step>
          <el-step title="商品内容"></el-step>
          <el-step title="完成"></el-step>
       </el-steps>
       <!-- tabs -->
       <el-form :model="addruleForm" :rules="addrules" ref="addForm" label-width="100px" label-position='top'>
         <el-tabs v-model="actives" :tab-position="'left'" :before-leave='beforeTab' @tab-click='tabClick'>
           <el-tab-pane label="基本信息" name='0'>
             <el-form-item label="商品名称" prop="goods_name">
               <el-input v-model="addruleForm.goods_name"></el-input>
             </el-form-item>
             <el-form-item label="商品价格" prop="goods_price">
               <el-input v-model="addruleForm.goods_price" type='number'></el-input>
             </el-form-item>
             <el-form-item label="商品重量" prop="goods_weight">
               <el-input v-model="addruleForm.goods_weight" type='number'></el-input>
             </el-form-item>
             <el-form-item label="商品数量" prop="goods_number">
               <el-input v-model="addruleForm.goods_number" type='number'></el-input>
             </el-form-item>
             <!-- 级联选择器 -->
             <el-form-item label='商品分类' prop='goods_cate'>
                 <el-cascader v-model="addruleForm.goods_cat" :options="cateList" :props="cateprops" @change="handleChange"></el-cascader>
             </el-form-item>

           </el-tab-pane>
           <el-tab-pane label="商品参数" name='1'>
             <el-form-item v-for="(item) in manytable" :key='item.attr_id' :label='item.attr_name'>
                 <!-- 复选框 -->
                  <el-checkbox-group v-model="item.attr_vals">
                     <el-checkbox :label="item1" v-for="(item1,index) in item.attr_vals" :key="index" border></el-checkbox>
                   </el-checkbox-group>
             </el-form-item>
            </el-tab-pane>
           <el-tab-pane label="商品属性" name='2'>
             <el-form-item v-for="(item) in onlytable" :key='item.attr_id' :label='item.attr_name'>
               <el-input v-model="item.attr_vals"></el-input>
             </el-form-item>
          </el-tab-pane>
           <el-tab-pane label="商品图片" name='3'>
             <el-upload :action="uploadurl" :on-preview="handlePreview" :on-remove="handleRemove" list-type="picture" :headers='headerobj' :on-success='handleSuccess'>
                 <el-button size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
             </el-upload>
           </el-tab-pane>
           <el-tab-pane label="商品内容" name='4'>
             <!-- 文本编辑器 -->
              <quill-editor ref="myQuillEditor" v-model="addruleForm.goods_introduce"/>
              <!-- 添加商品按钮 -->
              <el-button  type="primary" class="btn" @click="addgoods">添加商品</el-button>
           </el-tab-pane>
         </el-tabs>
       </el-form>
    </el-card >
     <!-- 图片预览 -->
     <el-dialog title="图片预览" :visible.sync="previevdialogVisible" width="50%">
         <img :src="previewpath" alt="" class="img">

      </el-dialog>
  </div>
</template>

<script>
import _ from 'loadsh'
export default {
data(){
  return{
    cateList:[],
    actives:"0",//激活的步骤条step
    addruleForm:{
      goods_name:'',
      goods_price:0,
      goods_weight:0,
      goods_number:0,
      goods_cat:[],//级联选择器选中数组
      pics:[],
      goods_introduce:'',
      attrs:[],

    },//添加的数据对象
    addrules:{
      goods_name:[ { required: true, message: '请输入商品名称', trigger: 'blur' },],
      goods_price:[ { required: true, message: '请输入商品价格', trigger: 'blur' },],
      goods_weight:[ { required: true, message: '请输入商品重量', trigger: 'blur' },],
      goods_number:[ { required: true, message: '请输入商品数量', trigger: 'blur' },],
      goods_cat:[ { required: true, message: '请选择商品分类', trigger: 'blur' },],
    },
    cateprops:{
      value:'cat_id',
      label:'cat_name',
      children:'children',
      expandTrigger:'hover',
      checkStrictly:true
    },//级联选择器配置
    manytable:[],
    onlytable :[],
    uploadurl:'http://127.0.0.1:9001/api/private/v1/upload',//上传地址
    headerobj:{Authorization:window.sessionStorage.getItem('token')},//请求头
    previewpath:'',
    previevdialogVisible:false,
  }
},
created(){
   this.getCateList()
},
computed:{
 cateid(){
   if (this.addruleForm.goods_cat.length === 3) {
     return this.addruleForm.goods_cat[2]
   }
   return null
 }
},
methods:{
/* 获取所有商品分类 */
async getCateList(){
  let {data:res} = await this.$http.get('categories')
  if (res.meta.status !==200) {
    return this.$message.error('获取分类失败')
  }
  this.cateList = res.data
 // console.log(res.data)
},
 //级联选择器选中变化触发
handleChange(){
  //console.log(this.addruleForm.goods_cat)
  if (this.addruleForm.goods_cat.length !==3) {
    this.addruleForm.goods_cat = []
  }
},
/*切换标签页触发  */
beforeTab(active,oldactive){
//console.log(active,oldactive)
if (oldactive === '0' && this.addruleForm.goods_cat.length !==3) {
  this.$message.error('请选择商品分类')
  return false
}

},
async tabClick(){
  if (this.actives === '1') {
    //选中的是动态参数
  let {data:res} = await this.$http.get(`categories/${this.cateid}/attributes`,{params:{sel:'many'}})
  if (res.meta.status !== 200) {
    return this.$message.error('获取动态参数失败')
  }
  res.data.forEach(element => {
   element.attr_vals = element.attr_vals.length === 0?'':element.attr_vals.split(' ')
  });
 this.manytable = res.data
 //console.log(this.manytable)    
  }else if (this.actives === '2') {
     //静态属性面板
       let {data:res} = await this.$http.get(`categories/${this.cateid}/attributes`,{params:{sel:'only'}})
       if (res.meta.status !== 200) {
       return this.$message.error('获取静态属性失败')
  }
          this.onlytable = res.data
          //console.log((res.data));
          
  }
},
/* 图片预览 */
handlePreview(file){
//console.log(file)
this.previewpath=file.response.data.url
this.previevdialogVisible = true
},
/* 删除图片的操作 */
handleRemove(file){
//获取临时路径
let filepath = file.response.data.tmp_path
//pics搜索
let index = this.addruleForm.pics.findIndex(x=>{
  x.pic ===filepath
})
this.addruleForm.pics.splice(index,1)
//console.log(this.addruleForm.pics)
},
/* 图片上传成功 拿到返回数据 */
handleSuccess(response){
  ///console.log(response)
   let pic = {pic:response.data.tmp_path}
   this.addruleForm.pics.push(pic)
  // console.log(this.addruleForm.pics)
},
 addgoods(){
  this.$refs.addForm.validate( async valid=>{
    if (!valid) {
      return this.$message.error('请填写必要的表单')
    }
    //添加
   
   let form = _.cloneDeep(this.addruleForm)
    form.goods_cat=form.goods_cat.join(',')
    //处理动态静态
    this.manytable.forEach(item=>{
      let info  = {attr_id:item.attr_id,attr_value:item.attr_vals.join(' ')}
      this.addruleForm.attrs.push(info)
    })
     this.onlytable.forEach(item=>{
      let info  = {attr_id:item.attr_id,attr_value:item.attr_vals}
      this.addruleForm.attrs.push(info)
    })
    form.attrs = this.addruleForm.attrs
    console.log(form)
     
     let {data:res} = await this.$http.post(`goods`,form)
     //数量不能为0 console.log(res.meta.status)
       if (res.meta.status !== 201) {
       return this.$message.error('添加商品失败')
          }
  this.$message.success('添加商品成功')
  this.$router.push('/goods')
  })
}




}
}
</script>

<style lang="less" scoped>
.el-checkbox.is-bordered+.el-checkbox.is-bordered,.el-checkbox.is-bordered.is-checked{
  margin: 0 5px 0 0;
}
.img{
  width: 100%;
}
.btn{
  margin-top: 15px;
}
</style>